
const {update_detail,front_log,front_log_img}=require('./api')

const addCookies = async (cookies_str, page, domain) => {
    let cookies = cookies_str.split(';').map(
        pair => {
        let name = pair.trim().slice(0, pair.trim().indexOf('='));
        let value = pair.trim().slice(pair.trim().indexOf('=') + 1);
        return {name, value, domain}
    });
    await Promise.all(cookies.map(pair => {
        return page.setCookie(pair)
    }))
};
const handle=async function(apply_no,browser){
    const page = await browser.newPage();
    return new Promise(async (res,rej)=>{

        await page.goto(
        `http://cpquery.cnipa.gov.cn/txnQueryFeeData.do?select-key:shenqingh=${apply_no}&
        select-key:zhuanlilx=${apply_no.toString().substr(4,1)}&
        select-key:gonggaobj=&
        inner-flag:open-type=window&
        inner-flag:flowno=${new Date().getTime()}`
        ,{  waitUntil:'domcontentloaded'})
        if(body=await page.$('body')){
            if(await page.$('.binding')){
                console.log(apply_no+'抓到binding了');
                const base64=await page.screenshot({
                    fullPage:true,
                    encoding:'base64'
                })
                const title=await page.$eval('.binding', html => html.outerHTML) || ''
                let res_str='error'
                front_log({msg:title})
                front_log_img({title:'多国查询'+apply_no+'失败,查询次数不够',base64:'data:image/png;base64,'+base64})
                if(title.includes('/images/reach_top.png'))
                    res_str='lack'
                else if(title.includes('/images/url_timeout.png'))
                    res_str='timeout'
                else 
                    res_str='empty'
                rej(res_str)
            }
            else if(await page.$('.tab_box')){
                res(await page.$eval('.tab_box', html => html.innerHTML))
            }else {
                rej('未知错误')
            }
        }else{
            console.log(apply_no,'白屏了')
            res(false)
        }
    })
    .then(fees=>{
        if(fees)
            return update_detail({ apply_no,fees})
    })
    .then(async res=>{
        await page.close()
        return res
    })
    .catch(async err=>{
        console.log(err);
        await browser.close()
    })
 
}
const appendFile=function(filePage,str){
    return new Promise((resolve,reject)=>{
        const fs=require('fs')
        fs.appendFile(filePage,str,function(error){
            if(error){
                reject(error)
            }
            resolve(true)
        })
    })
    .catch(err=>{
        close_fn({msg:'文件写入失败',err})
    })
}
const close_fn=function(str){
    console.log(str);
    process.exit()
}
module.exports={
    appendFile,
    close_fn,
    addCookies,
    handle,

}
